package spring.batch.readFile;

import org.apache.commons.io.FileUtils;
import org.springframework.batch.core.annotation.OnSkipInProcess;
import org.springframework.batch.core.annotation.OnSkipInRead;
import org.springframework.batch.core.annotation.OnSkipInWrite;
import org.springframework.batch.item.file.FlatFileParseException;

import java.io.File;
import java.io.IOException;

/**
 * @Author: huhx
 * @Date: 2017-11-01 下午 5:32
 */
public class FileSkipListener {
    private File file = new File("file/log.txt");

    @OnSkipInRead
    public void readLog(Throwable t) throws IOException {
        if (t instanceof FlatFileParseException) {
            FlatFileParseException ffpe = (FlatFileParseException) t;
            String dataLog = "from read " + ffpe.getInput() + ", line number = " + ffpe.getLineNumber() + "\n";
            FileUtils.write(file, dataLog, true);
        }
    }

    @OnSkipInProcess
    public void processLog(People people, Throwable t) throws IOException {
        if (t instanceof FlatFileParseException) {
            FlatFileParseException ffpe = (FlatFileParseException) t;
            String dataLog = "from process " + ffpe.getInput() + ", line number = " + ffpe.getLineNumber() + "\n";
            String peopleInfo = people.getUsername() + ", address " + people.getBirthday() + "\n";
            FileUtils.write(file, dataLog + peopleInfo, true);
        }
    }

    @OnSkipInWrite
    public void writeLog(People people, Throwable t) throws IOException {
        if (t instanceof FlatFileParseException) {
            FlatFileParseException ffpe = (FlatFileParseException) t;
            String dataLog = "from write " + ffpe.getInput() + ", line number = " + ffpe.getLineNumber() + "\n";
            String peopleInfo = people.getUsername() + ", address " + people.getBirthday() + "\n";
            FileUtils.write(file, dataLog + peopleInfo, true);
        }
    }
}
